import "./kWidget.css";
import { render, templateRender ,getType} from "./utils/base";

class Kwidget extends HTMLElement {
    constructor() {
        super();
    }

    initShadow() {
        const shadowRoot = this.attachShadow({ mode: "open" });
        const sheet = new CSSStyleSheet();
        sheet.replaceSync(this.css());
        shadowRoot.adoptedStyleSheets = [sheet];
        getType(this.html()) === "string" ? templateRender(this.html(), shadowRoot) : render(this.html(), shadowRoot);
        return shadowRoot;
    }

    registerEvent(evtType, callback) {
        try {
            this.addEventListener(evtType, (e) => {
                callback(e.target.value)
            });
        } catch (err) {
            throw new Error(`${evtType}事件注册失败`);
        }
    }

    parse(json) { 
        return JSON.parse(json);
    }

    stringify(json) {
        return JSON.stringify(json);
    }

    html() {}
    
    css() {}

    static defineCustomElement(name, clazz) {
        if (customElements.get(name)) return new Error(`${name} 组件已存在`);
        customElements.define(name, clazz);
    }

    logInfo(text = "挂载") {
        console.log(`%c${text}`, 'color: green;border:1px solid rgba(103, 194, 58, 1);font-size: 12px; font-family: Alibaba PuHuiTi;  background-color: rgba(103, 194, 58, 0.3);padding: 4px 5px;border-radius: 3px;');
    }
}

export { Kwidget };